<template>
    <div class="page">
        <div class="logo">
            <img class="logo-img" src="../assets/userLogo-2.png" alt="" />
            <div class="tab-app" @click="goPage('customer')" v-if="userinfo.type !== 1">
                <img src="../assets/119.png" alt="" />
                <span>{{ $t("language.text10") }}</span>
            </div>
            <div class="right-ic" @click="changeLanguage">
                <img src="../assets/100-1.png" alt="" />
                <span>{{ $i18n.locale == "zh" ? "EN" : "中文" }}</span>
                <div class="out" @click="tapOut">{{ $t("language.text76") }}</div>
            </div>
        </div>
        <van-swipe class="my-swipe" :autoplay="5000" :show-indicators="false">
            <van-swipe-item v-for="(item, index) in bannerList" @click="tapBanner(item)" :key="index">
                <img v-lazy="item.image" />
            </van-swipe-item>
        </van-swipe>
        <div class="user">
            <div class="user-left">
                <div class="user-name">
                    {{ userinfo.name }}
                    <span class="en">{{ userinfo.english_name }}</span>
                    <!-- <span class="tag">{{userinfo.position}}</span> -->
                </div>

                <!-- <div class="user-text" v-if="showHotelsTab">{{hotel_name}}</div> -->
                <div class="content-tab" v-if="showHotelsTab" @click="showPopup = !showPopup">
                    <img class="ic" src="../assets/tab-ic.png" alt="" />
                    {{ $t("language.text73") }}：<span>{{ hotel_name }}</span>
                </div>
            </div>
            <div class="user-img">
                <img :src="userinfo.avatar" alt="" />
            </div>
        </div>
        <div class="content">
            <!-- <div class="content-tab" v-if="showHotelsTab" @click="showPopup = !showPopup">
				<img class="ic" src="../assets/tab-ic.png" alt="" />
				{{$t('language.text73')}}：<span>{{hotel_name}}</span>
			</div> -->
            <div class="search-wrap">
                <!-- <div class="tab-text">
					{{$t('language.text11')}}
					<img class="ic" src="../assets/120.png" alt="" />
				</div> -->
                <div class="search">
                    <input type="text" v-model="search" :placeholder="$t('language.search')" />
                    <img class="ic" src="../assets/101.png" alt="" />
                </div>
            </div>
            <van-list v-model="loading" :finished="finished" :finished-text="$t('language.noMore')" @load="onLoad">
                <div class="card" @click="goPage('details', item.id)" v-for="item in list" :key="item.id">
                    <div class="title" v-if="item.title">{{ item.title || "" }}</div>
                    <div class="title small">{{ item.title_alias || "" }}</div>
                    <div class="tag-wrap">
                        <!-- is_verify 0 待审核 1 成功 2 失败 -->
                        <div v-if="item.is_verify == 0" class="tag await">{{ $t("language.text12") }}</div>
                        <div v-if="item.is_verify == 1" class="tag success">{{ $t("language.text13") }}</div>
                        <div v-if="item.is_verify == 2" class="tag not">{{ $t("language.text14") }}</div>
                        <!-- <div class="tag">长期客户</div> -->
                    </div>
                    <div class="info">
                        {{ $i18n.locale == "zh" ? `${computeDate(item.created_at) + $t("language.text15") }` : `${ $t("language.text15") + computeDate(item.created_at)}` }}: <span class="num">{{ item.room_num || item.be_room_num }}</span>
                    </div>
                    <div class="info top-10">
                        {{ $t("language.text32") }}: <span class="num">{{ item.price_code }}</span>
                    </div>
                    <!-- is_share 这个是是否开启分享 0 不开 1开 -->
                    <div class="btn" v-if="item.is_share == 1" @click.stop="tapShare(item)">
                        {{ $t("language.text16") }}
                    </div>
                    <div class="btn not" v-if="item.is_share == 0" @click.stop="">{{ $t("language.text16") }}</div>
                </div>
            </van-list>
        </div>

        <div class="add-btn" v-if="hotels.length > 0 || !showHotelsTab">
            <div class="btn" @click="goPage('addInr')">{{ $t("language.text17") }}</div>
        </div>
        <van-popup v-model="showPopup" position="bottom">
            <div class="popup-hotels">
                <van-picker
                    show-toolbar
                    :confirm-button-text="$t('language.text52')"
                    :cancel-button-text="$t('language.text53')"
                    value-key="hotel_name"
                    :default-index="hotel_index"
                    :columns="hotels"
                    @cancel="showPopup = !showPopup"
                    @confirm="onConfirm"
                />
            </div>
        </van-popup>
    </div>
</template>
<script>
import { getToken, removeToken } from "@/utils/auth";
import {
    getUserInfo,
    getLnr,
    openMsg,
    // getWxConfig,
    getWxAgentConfig,
    share,
    beLnrLists,
    banner,
    be_share,
} from "@/api/user";
import {
    Dialog,
    // Toast
} from "vant";

let timer = null;
export default {
    name: "Index",
    data: function () {
        return {
            locale: "zh",
            search: "",
            showPopup: false,
            userinfo: {
                type: 1,
                hotel: {},
            },
            type: 0,
            list: [],
            hotels: [],
            loading: false,
            finished: false,
            showHotelsTab: false,
            page: 1,
            hotel_id: "",
            hotel_name: "",
            hotel_code: "",
            hotel_index: 0,
            bannerList: [],
        };
    },
    watch: {
        search: function () {
            const t = this;
            if (timer != null) clearTimeout(timer);

            timer = setTimeout(() => {
                timer = null;
                clearTimeout(timer);
                t.page = 1;
                t.list = [];
                t.getLnrData();
            }, 500);
        },
    },
    created() {
        let userinfo = JSON.parse(localStorage.getItem("userinfo"));
        if (userinfo) {
            const { type } = userinfo;
            this.type = type;
            this.userinfo = userinfo;
            this.showHotelsTab = type !== 4 ? true : false;
            if (userinfo.is_open_msg == 0) {
                Dialog.alert({
                    title: this.$i18n.tc("language.text18"),
                    message: this.$i18n.tc("language.text19"),
                    theme: "round-button",
                    confirmButtonText: this.$i18n.tc("language.text20"),
                }).then(() => {
                    userinfo.is_open_msg = 1;
                    localStorage.setItem("userinfo", JSON.stringify(userinfo));
                    this.getOpenMsg();
                });
            }
        }

        this.wxConfig();
        this.getBanner();
    },
    mounted() {},
    methods: {
		computeDate(str) {
			let date = new Date(str);
			date.setMonth(date.getMonth() - 1);
			return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}`;
		},
        tapBanner(item) {
            if (item.url == null) return;
            window.location.href = `${item.url}?key=Bearer ${getToken()}`;
        },
        tapOut() {
            removeToken();
            localStorage.removeItem("userinfo");
            localStorage.removeItem("hotels");
            this.$router.replace(`/login`);
        },
        onConfirm(value, index) {
            const { hotel_id, hotel_name, hotel_code } = value;
            this.page = 1;
            this.list = [];
            value.hotel_index = index;
            this.hotel_id = hotel_id;
            this.hotel_name = hotel_name;
            this.hotel_code = hotel_code;
            this.hotel_index = index;
            this.showPopup = false;
            localStorage.setItem("hotels", JSON.stringify(value));
            this.getLnrData();
        },
        wxConfig() {
            getWxAgentConfig({
                url: location.href.split("#")[0],
                code: "launchMiniprogram,checkJsApi",
            })
                .then((res) => {
                    const data = JSON.parse(res.data);
                    wx.agentConfig({
                        corpid: "wwdc0bc731d475dfb8", // 必填，企业微信的corpid，必须与当前登录的企业一致
                        agentid: "1000156", // 必填，企业微信的应用id （e.g. 1000247）
                        timestamp: data.timestamp, // 必填，生成签名的时间戳
                        nonceStr: data.nonceStr, // 必填，生成签名的随机串
                        signature: data.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
                        jsApiList: ["launchMiniprogram", "checkJsApi"], //必填，传入需要使用的接口名称
                        success: function () {
                            // console.log(res, 'agentConfig---success')
                        },
                        fail: function (err) {
                            // console.log(err, 'agentConfig---fail')
                            if (err.errMsg.indexOf("function not exist") > -1) {
                                console.log(err.errMsg, "fail");
                            }
                        },
                    });
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        tapShare(item) {
            let page = '';
            if (this.type == 4) {
                page = `pages/home/home?corporateId=${item.agreement_price_code}`;
            } else {
				page = `bookingFlow/hotelDetail/hotelDetail?hotelCode=${this.hotel_code}&commercialCorporateId=${item.agreement_price_code}&utm_source=${item.user.merlinid}`;
			}
            wx.invoke(
                "launchMiniprogram",
                {
                    appid: "wx6c93945039c16dec", // 需跳转的小程序appid
                    path: page, // 所需跳转的小程序内页面路径及参数。非必填
                },
                (res) => {
                    if (res.err_msg == "launchMiniprogram:ok") {
                        if (this.type != 4) {
                            share({
                                lnr_id: item.id,
                            })
                                .then(() => {})
                                .catch(() => {});
                        } else {
                            be_share({
                                be_lnr_id: item.id,
                            })
                                .then(() => {})
                                .catch(() => {});
                        }
                    }
                }
            );
        },
        getOpenMsg() {
            openMsg()
                .then(() => {})
                .catch(() => {});
        },
        getBanner() {
            banner()
                .then((res) => {
                    this.bannerList = res.data;
                })
                .catch(() => {});
        },
        onLoad() {
            this.getLnrData();
        },
        async getLnrData() {
            if (this.type !== 4) {
                if (this.hotels.length == 0) {
                    const user = await getUserInfo();
                    this.userinfo = user.data;
                    this.hotels = user.data.hotels;
                    let _hotels = localStorage.getItem("hotels");
                    if (user.data.hotels.length > 0) {
                        if (_hotels) {
                            _hotels = JSON.parse(_hotels);
                        } else {
                            _hotels = user.data.hotels[0];
                        }
                        this.hotel_id = _hotels.hotel_id;
                        this.hotel_name = _hotels.hotel_name;
                        this.hotel_code = _hotels.hotel_code;
                        if (!_hotels.hotel_index) {
                            _hotels.hotel_index = 0;
                        }
                        this.hotel_index = _hotels.hotel_index;
                        localStorage.setItem("hotels", JSON.stringify(_hotels));
                    }
                }

                getLnr({
                    page: this.page,
                    key: this.search,
                })
                    .then((res) => {
                        let { current_page, last_page, data } = res.data;
                        // 加载状态结束
                        this.loading = false;
                        // 数据全部加载完成
                        if (current_page == last_page) {
                            this.finished = true;
                        } else {
                            this.finished = false;
                            this.page++;
                        }
                        this.list = [...this.list, ...data];
                    })
                    .catch((err) => {
                        console.log(err);
                        this.loading = false;
                    });
                return;
            }
            beLnrLists({
                page: this.page,
                key: this.search,
            })
                .then((res) => {
                    let { current_page, last_page, data } = res.data;
                    // 加载状态结束
                    this.loading = false;
                    // 数据全部加载完成
                    if (current_page == last_page) {
                        this.finished = true;
                    } else {
                        this.finished = false;
                        this.page++;
                    }
                    this.list = [...this.list, ...data];
                })
                .catch((err) => {
                    console.log(err);
                    this.loading = false;
                });
        },
        goPage(page, id) {
            this.$router.push({
                path: page,
                query: {
                    id,
                },
            });
        },
        changeLanguage() {
            if (this.$i18n.locale == "zh") {
                this.$i18n.locale = "en";
                this.$cookies.set("locale", "en");
            } else {
                this.$i18n.locale = "zh";
                this.$cookies.set("locale", "zh");
            }
        },
    },
};
</script>
<style type="text/css" lang="scss" scoped>
.page {
    background-color: #fff;
}

.logo {
    background-color: #fff;

    .tab-app {
        display: flex;
        align-items: center;
        font-size: 24px;
        color: #333333;

        img {
            width: 31px;
            height: 30px;
            margin-right: 6px;
        }
    }

    .right-ic {
        color: #333333;
    }

    .out {
        font-size: 24px;
        color: #333333;
        margin-left: 24px;
    }
}

.my-swipe {
    height: 310px;
    .van-swipe-item {
        height: 310px;
        img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
    }
}

.user {
    width: 92%;
    height: 200px;
    position: relative;
    top: -30px;
    left: 50%;
    z-index: 10;
    transform: translateX(-50%);
    display: flex;
    justify-content: flex-end;
    align-items: center;
    flex-direction: row-reverse;
    background-color: #fff;
    box-shadow: 0 4px 24px #eeeeee;
    border-radius: 8px;

    .user-left {
        color: #333333;

        .user-name {
            font-size: 36px;

            .tag {
                position: relative;
                top: 4px;
                margin-left: 12px;
                display: inline-block;
                max-width: 300px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                padding: 8px 12px;
                border-radius: 18px 18px 18px 0;
                font-size: 20px;
                background-color: #e8542c;
            }
        }

        .user-text {
            margin-top: 10px;
            font-size: 24px;
        }

        .content-tab {
            display: flex;
            align-items: center;
            font-size: 22px;
            color: #1f4456;
            margin-top: 4px;

            .ic {
                width: 24px;
                height: 24px;
                margin-right: 12px;
            }
        }
    }

    .user-img {
        width: 120px;
        height: 120px;
        flex-shrink: 0;
        margin: 0 24px;
        border-radius: 50%;
        border: 1px solid #fff;
        overflow: hidden;

        img {
            width: 100%;
            height: 100%;
        }
    }
}

.content {
    position: relative;
    // top: -50px;
    // left: 0;
    // z-index: 100;
    padding-bottom: 80px;
    background-color: #fff;
    border-radius: 30px 30px 0 0;

    // .content-tab {
    // 	display: flex;
    // 	align-items: center;
    // 	margin: 0 30px;
    // 	padding-top: 50px;
    // 	font-size: 30px;

    // 	.ic {
    // 		width: 32px;
    // 		height: 33px;
    // 		margin-right: 12px;
    // 	}
    // }

    .search-wrap {
        padding-top: 40px;
        padding-bottom: 16px;
        margin: 0 30px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .tab-text {
            font-size: 30px;
            color: #666666;

            .ic {
                width: 14px;
                height: 10px;
                margin-left: 12px;
                position: relative;
                top: -4px;
            }
        }

        .search {
            position: relative;
            z-index: 10;
            padding: 0 28px;
            width: 100%;
            height: 74px;
            // margin-left: 24px;
            border: 2px solid #1f4456;
            background-color: #fff;
            box-sizing: border-box;
            border-radius: 45px;
            display: flex;
            align-items: center;
            justify-content: space-between;

            input {
                font-size: 24px;
                color: #666;
                width: 100%;
                height: 100%;
            }

            .ic {
                width: 28px;
                height: 28px;
                flex-shrink: 0;
            }
        }
    }

    .card {
        margin: 24px 30px 0;
        padding: 30px;
        box-sizing: border-box;
        border-radius: 10px;
        box-shadow: 0 0 24px #eee;
        position: relative;

        .title {
            font-size: 30px;
            color: #333333;
            padding-bottom: 24px;
            font-weight: bold;

            &.small {
                font-size: 24px;
                margin-top: 8px;
            }
        }

        .tag-wrap {
            display: flex;
            flex-wrap: wrap;

            .tag {
                padding: 8px 18px;
                border-radius: 0 8px 8px 8px;
                color: #e8542c;
                font-size: 22px;
                margin-right: 12px;
                background-color: #fbe8e2;

                &.not {
                    color: #fff;
                    background-color: #f01a1a;
                }

                &.success {
                    color: #fff;
                    background-color: #09bb00;
                }

                &.await {
                    color: #fff;
                    background-color: #e8542c;
                }
            }
        }

        .info {
            margin-top: 24px;
            font-size: 24px;
            color: #666666;

            .num {
                color: #1f4456;
            }

            &.top-10 {
                margin-top: 10px;
            }
        }

        .btn {
            position: absolute;
            right: 30px;
            bottom: 30px;
            color: #fff;
            font-size: 28px;
            padding: 12px 24px;
            border-radius: 10px;
            background-color: #1f4456;

            &.not {
                background-color: #babfc1;
            }
        }
    }
}

.add-btn {
    position: fixed;
    left: 50%;
    bottom: 0;
    transform: translateX(-50%);
    z-index: 1000;
    width: 100%;
    height: 114px;
    max-width: 750px !important;
    color: #fff;
    font-size: 28px;
    background-color: #fff;
    box-shadow: 0 2px 24px #eee;
    padding: 14px 30px;

    .btn {
        width: 100%;
        padding: 21px 0;
        border-radius: 10px;
        text-align: center;
        background-color: #e8542c;
    }
}
</style>
